package com.my.sort;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by ZhongGang
 * at 2018/10/8 16:37
 * <p>
 * 冒泡排序
 * 1. 依次比较相邻的两个数组元素
 * 2. 如果后一元素小于前一元素，则交换两个元素，经过一轮后最大的元素排在最后
 * 3. 对于余下的数组元素重复步骤1，2
 * <p>
 * 复杂度 N的平方
 */
public class BubbleSorter<T extends Comparable<T>> implements Sortable<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(BubbleSorter.class);

    @Override
    public T[] sort(T[] elements) {
        if (elements == null || elements.length < 2) {
            return elements;
        }

        int length = elements.length;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length - 1 - i; j++) {
                if (elements[j].compareTo(elements[j + 1]) > 0) {
                    T tmp = elements[j];
                    elements[j] = elements[j + 1];
                    elements[j + 1] = tmp;
                }
                LOGGER.info("i: {}, j: {}, elements: {}", i, j, elements);
            }
        }

        return elements;
    }
}
